import * as React from "react";
import {
  StyleSheet,
  View,
  ProgressViewIOS,
  TouchableOpacity,
  Platform,
  Dimensions
} from "react-native";
import { WebView } from "react-native-webview";
import Icon from "react-native-vector-icons/FontAwesome";
import Bar from "react-native-progress/Bar";

import NavigationService from "../Service/NavigationService";

const { width } = Dimensions.get("window");

interface Props extends React.Props<any> {
  navigation: any;
}

interface State {
  progress: number;
}

export default class MyWebView extends React.Component<Props, State> {
  static navigationOptions: any = ({ navigation }) => {
    return {
      title: navigation.state.params.title ? navigation.state.params.title : "",
      headerLeft: (
        <TouchableOpacity
          onPress={() =>
            navigation.state.params.canGoBack === true
              ? navigation.state.params.goBackFunc()
              : NavigationService.pop()
          }
        >
          <Icon
            style={{ marginLeft: 20 }}
            name="angle-left"
            size={30}
            color="white"
          />
        </TouchableOpacity>
      )
    };
  };

  _webView: any = null;

  constructor(props: Props) {
    super(props);
    this.state = {
      progress: 0.0
    };
  }

  render() {
    const url = this.props.navigation.getParam("url", "https://sina.cn");

    let progressView: any = null;
    if (this.state.progress < 1.0 && this.state.progress >= 0) {
      if (Platform.OS === "ios") {
        progressView = (
          <ProgressViewIOS
            progress={this.state.progress}
            progressTintColor="green"
            trackTintColor="#EFEFEF"
            progressViewStyle="default"
            style={{ height: 1.0 }}
          />
        );
      } else {
        progressView = (
          <Bar
            progress={this.state.progress}
            color="green"
            width={width}
            height={1.0}
            borderRadius={0}
            borderWidth={0}
          />
        );
      }
    }
    return (
      <View style={styles.container}>
        {progressView}
        <WebView
          style={styles.webViewStyle}
          ref={(ref: any) => {
            this._webView = ref;
          }}
          source={{ uri: encodeURI(url) }}
          onLoadProgress={(e: any) => {
            this.setState({ progress: e.nativeEvent.progress });
          }}
          onError={(e: any) => {
            console.warn(`WebView load error: ${e}`);
            // 加载失败时，可以返回上一级页面
            this.props.navigation.setParams({ canGoBack: false });
          }}
          onNavigationStateChange={this._handleWebViewNavigationStateChange}
          startInLoadingState={false}
          // renderError={() => {
          //   return <View />;
          // }}
        />
      </View>
    );
  }

  _handleWebViewNavigationStateChange = (newNavState: any) => {
    const { title } = newNavState;
    this.props.navigation.setParams({ title: title });

    const { canGoBack } = newNavState;
    this.props.navigation.setParams({ canGoBack: canGoBack });
    if (canGoBack === true) {
      this.props.navigation.setParams({
        goBackFunc: () => {
          this._webView.goBack();
          setTimeout(() => {
            // 更新web view状态
            this._webView.reload();
          }, 200.0);
        }
      });
    }
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  webViewStyle: {
    width: "100%",
    height: "100%",
    justifyContent: "center",
    alignItems: "center"
  }
});
